package com.example.demo.controller;

import com.example.demo.dto.ResponseResult;
import com.example.demo.model.User;
import com.example.demo.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.List;

@RestController
@RequestMapping("/api/users")
public class UserController {

    @Autowired
    private UserService userService;

    /**
     * 获取所有用户列表
     * GET http://localhost:8080/api/users
     */
    @GetMapping("")
    public ResponseResult<List<User>> getAllUsers() {
        try {
            List<User> users = userService.getAllUsers();
            return ResponseResult.success("获取用户列表成功", users);
        } catch (Exception e) {
            return ResponseResult.error("获取用户列表失败: " + e.getMessage());
        }
    }

    /**
     * 根据ID获取用户详情
     * GET http://localhost:8080/api/users/1
     */
    @GetMapping("/{id}")
    public ResponseResult<User> getUserById(@PathVariable Long id) {
        try {
            User user = userService.getUserById(id);
            if (user != null) {
                return ResponseResult.success("获取用户成功", user);
            } else {
                return ResponseResult.error(404, "用户不存在");
            }
        } catch (Exception e) {
            return ResponseResult.error("获取用户失败: " + e.getMessage());
        }
    }

    /**
     * 创建新用户
     * POST http://localhost:8080/api/users
     * Body: JSON格式的用户信息
     */
    @PostMapping("")
    public ResponseResult<User> createUser(@RequestBody User user) {
        try {
            // 验证必填字段
            if (user.getName() == null || user.getName().trim().isEmpty()) {
                return ResponseResult.error(400, "用户姓名不能为空");
            }
            if (user.getEmail() == null || user.getEmail().trim().isEmpty()) {
                return ResponseResult.error(400, "邮箱不能为空");
            }

            // 检查邮箱是否已存在
            if (userService.isEmailExists(user.getEmail())) {
                return ResponseResult.error(400, "邮箱已存在");
            }

            User createdUser = userService.createUser(user);
            return ResponseResult.success("创建用户成功", createdUser);
        } catch (Exception e) {
            return ResponseResult.error("创建用户失败: " + e.getMessage());
        }
    }

    /**
     * 更新用户信息
     * PUT http://localhost:8080/api/users/1
     * Body: JSON格式的用户信息
     */
    @PutMapping("/{id}")
    public ResponseResult<User> updateUser(@PathVariable Long id, @RequestBody User userDetails) {
        try {
            // 检查用户是否存在
            User existingUser = userService.getUserById(id);
            if (existingUser == null) {
                return ResponseResult.error(404, "用户不存在");
            }

            // 验证必填字段
            if (userDetails.getName() == null || userDetails.getName().trim().isEmpty()) {
                return ResponseResult.error(400, "用户姓名不能为空");
            }

            User updatedUser = userService.updateUser(id, userDetails);
            return ResponseResult.success("更新用户成功", updatedUser);
        } catch (Exception e) {
            return ResponseResult.error("更新用户失败: " + e.getMessage());
        }
    }

    /**
     * 删除用户
     * DELETE http://localhost:8080/api/users/1
     */
    @DeleteMapping("/{id}")
    public ResponseResult<String> deleteUser(@PathVariable Long id) {
        try {
            // 检查用户是否存在
            User existingUser = userService.getUserById(id);
            if (existingUser == null) {
                return ResponseResult.error(404, "用户不存在");
            }

            boolean isDeleted = userService.deleteUser(id);
            if (isDeleted) {
                return ResponseResult.success("删除用户成功", null);
            } else {
                return ResponseResult.error("删除用户失败");
            }
        } catch (Exception e) {
            return ResponseResult.error("删除用户失败: " + e.getMessage());
        }
    }

    /**
     * 根据姓名搜索用户
     * GET http://localhost:8080/api/users/search?name=张三
     */
    @GetMapping("/search")
    public ResponseResult<List<User>> searchUsersByName(@RequestParam String name) {
        try {
            if (name == null || name.trim().isEmpty()) {
                return ResponseResult.error(400, "搜索关键词不能为空");
            }

            List<User> users = userService.searchUsersByName(name);
            return ResponseResult.success("搜索成功", users);
        } catch (Exception e) {
            return ResponseResult.error("搜索失败: " + e.getMessage());
        }
    }

    /**
     * 获取用户统计信息
     * GET http://localhost:8080/api/users/stats
     */
    @GetMapping("/stats")
    public ResponseResult<String> getUserStats() {
        try {
            int userCount = userService.getUserCount();
            return ResponseResult.success("获取统计成功",
                    String.format("当前系统共有 %d 个用户", userCount));
        } catch (Exception e) {
            return ResponseResult.error("获取统计失败: " + e.getMessage());
        }
    }

    /**
     * 健康检查接口
     * GET http://localhost:8080/api/users/health
     */
    @GetMapping("/health")
    public ResponseResult<String> healthCheck() {
        return ResponseResult.success("用户服务运行正常", null);
    }
}